#include <gtk/gtk.h>

#include "tscell.h"
#include "tsdna.h"
#include "tsapp.h"

struct _TsApp
{
  GtkApplication parent;
};

G_DEFINE_TYPE(TsApp, ts_app, GTK_TYPE_APPLICATION);

static void
ts_app_init (TsApp *ts_app)
{
}


static void
ts_app_startup (GApplication *ts_app)
{
  G_APPLICATION_CLASS (ts_app_parent_class)->startup (ts_app);
}

static void
ts_app_activate (GApplication *ts_app)
{
  TsDna *dnas = NULL, *dna = NULL, *dna_next = NULL;
  TsCell *cell = NULL;
  gint64 id, threshold;

  g_debug ("hello template\n");

  dnas = ts_dna_from_sql ("dna.db");
  g_debug ("L%d f-%s dnas:%p", __LINE__, __func__, dnas);
  dna = dnas;
  while (dna) {
    g_object_get (dna, "id", &id, "next", &dna_next, "threshold", &threshold, NULL);
    cell = ts_cell_new ((gpointer)dnas, id, threshold);
    g_object_set (dna, "cell", cell, NULL);
    dna = dna_next;
  }
  dna = dnas;
  while (dna) {
    g_object_get (dna, "id", &id, "next", &dna_next, "cell", &cell, NULL);
    ts_cell_synapse_link (cell);
    dna = dna_next;
  }
  ts_dna_cell_set_axon_value (dnas, 1, 1, 3, NULL);
  /*
  //id 1:in 0:out
  GList *in_list = NULL, *l = NULL;
  gint64 t = 1, cell_id = 0;
    //g_object_set (cell, "value", value, "time", time_str, "space", space, NULL);
    g_object_get (cell, "id", &cell_id, "dendrite", &dendrite, NULL);
    if (cell_id == 2) {
      lidx = g_list_nth (dendrite, 1);
      synapse = lidx->data;
      g_object_set (synapse, "value", 24, NULL);
      g_object_set (cell, "dendrite", dendrite, NULL);
    } else if (cell_id == 3) {
    } else {
      g_object_set (cell, "value", 23, NULL);
    }
    */
 // ts_cell_run (cell);

  g_main_loop_run (g_main_loop_new (NULL, FALSE));
}

static void
ts_app_open (GApplication  *ts_app,
                  GFile        **files,
                  gint           n_files,
                  const gchar   *hint)
{
}

static void
ts_app_class_init (TsAppClass *class)
{
  G_APPLICATION_CLASS (class)->startup = ts_app_startup;
  G_APPLICATION_CLASS (class)->activate = ts_app_activate;
  G_APPLICATION_CLASS (class)->open = ts_app_open;
}

TsApp *
ts_app_new (void)
{
  return g_object_new (TS_APP_TYPE,
                       "application-id", "org.gtk.ts_app",
                       "flags", G_APPLICATION_HANDLES_OPEN,
                       NULL);
}
